package cc.kzc.adminauth.auth.service.impl;

import java.util.HashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import cc.kzc.adminauth.auth.JwtProcessor;
import cc.kzc.adminauth.auth.bo.LoginUser;
import cc.kzc.adminauth.auth.service.LoginService;
import cc.kzc.adminauth.auth.vo.UserReq;
import cc.kzc.adminauth.common.BaseResponse;
import cc.kzc.adminauth.common.ErrorCode;
import cc.kzc.adminauth.exception.BaseError;
import cc.kzc.adminauth.redis1.cache.LoginUserCache;

@Service
public class LoginServiceImpl implements LoginService {

	@Autowired
	private AuthenticationManager authenticationManager;

	@Autowired
	private LoginUserCache loginUserCache;

	@Override
	public BaseResponse login(UserReq user) {
		UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
				user.getUser(), user.getPassword());
		// 认证
		Authentication authenticate = authenticationManager.authenticate(authenticationToken);
		if (null == authenticate) {
			throw new BaseError(ErrorCode.CLI_UNAUTHORIZED, "用户名或密码错误");
		}
		// 使用userid生成token
		LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
		String userId = loginUser.getUser().getUid();
		String jwt = JwtProcessor.createJWT(userId);
		// authenticate存入redis
		loginUserCache.set(userId, loginUser);
		// 把token响应给前端
		HashMap<String, String> map = new HashMap<>();
		map.put("token", jwt);

		return BaseResponse.success(map);
	}

	@Override
	public BaseResponse logout(UserReq user) {
		return BaseResponse.success();
	}
}
